package org.snail.activemq.listener;

import com.alibaba.fastjson.JSON;
import com.dingtalk.open.client.api.model.corp.MessageBody;
import com.dingtalk.open.client.api.model.corp.MessageType;
import lombok.extern.log4j.Log4j;
import org.snail.attendence.bean.AbAttendenceMongo;
import org.snail.attendence.bean.AbnormalAttendanceDTO;
import org.snail.common.dingding.Env;
import org.snail.common.dingding.auth.AuthHelper;
import org.snail.common.dingding.chat.UserMessageHelper;
import org.snail.employee.bean.EmpCondition;
import org.snail.employee.bean.EmployeesDO;
import org.snail.employee.mapper.EmployeesMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Component;

import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageListener;
import javax.jms.TextMessage;
import java.util.*;

@Log4j
@Component("attendenceAbnormalListener")
@PropertySource("classpath:context-datasource.properties")
public class AbnormalSenderListener implements MessageListener {
    @Autowired
    private EmployeesMapper employeesMapper;
    @Value("${server.online.abnormalSenderFlag}")
    private int abnormalSenderFlag;
    private static int count = 0;

    @Override
    public void onMessage(Message message) {
        log.error("[attendenceAbnormalListener.onMessage]:begin onMessage.");
        TextMessage textMessage = (TextMessage) message;
        if(abnormalSenderFlag==1) {
            String jsonStr = null;
            try {
                jsonStr = textMessage.getText();
            } catch (JMSException e) {
                log.error("AttendenceAbnormalListener:37 消息队列获取消息出错");
            }

            if (jsonStr != null) {
                AbAttendenceMongo abAttendenceMongo = JSON.parseObject(jsonStr, AbAttendenceMongo.class);
                List<AbnormalAttendanceDTO> abnormalAttendanceList = abAttendenceMongo.getAbnormalAttendanceDTOList();
                Map<Integer, Map<String, List<AbnormalAttendanceDTO>>> empIdMap = new HashMap<>();
                for (AbnormalAttendanceDTO abnormalAttendanceDTO : abnormalAttendanceList) {
                    Integer empId = abnormalAttendanceDTO.getEmpId();
                    String abnormalityOfAttendanceDescribe = abnormalAttendanceDTO.getAbnormalityOfAttendanceDescribe();
                    if (empIdMap.get(empId) == null) {
                        empIdMap.put(empId, new HashMap<>());
                    }
                    if (empIdMap.get(empId).get(abnormalityOfAttendanceDescribe) == null) {
                        empIdMap.get(empId).put(abnormalityOfAttendanceDescribe, new ArrayList<>());
                    }
                    empIdMap.get(empId).get(abnormalityOfAttendanceDescribe).add(abnormalAttendanceDTO);
                }

                for (Integer empId : empIdMap.keySet()) {
                    StringBuilder sb = new StringBuilder();
                    Map<String, List<AbnormalAttendanceDTO>> m = empIdMap.get(empId);
                    String empName = "";
                    Set<String> describeSet = m.keySet();
                    Iterator it = describeSet.iterator();
                    while (it.hasNext()) {
                        List<AbnormalAttendanceDTO> abs = m.get(it.next());
                        empName = abs.get(0).getEmployeeName();
                        sb.append(empName + "  ");
                        break;
                    }
                    for (String desStr : describeSet) {
                        sb.append(desStr + ":");
                        List<AbnormalAttendanceDTO> abnormalAttendanceDTOs = m.get(desStr);
                        for (AbnormalAttendanceDTO abnormalAttendanceDTO : abnormalAttendanceDTOs) {
                            sb.append(abnormalAttendanceDTO.getDateStr() + ",");
                        }
                    }
                    EmpCondition empCondition = new EmpCondition();
                    empCondition.setEmpId(empId);
                    List<EmployeesDO> employeesDOs = employeesMapper.findAllEmp(empCondition);
                    if (employeesDOs == null) {
                        continue;
                    }
                    if (employeesDOs.get(0) == null) {
                        continue;
                    }
                    String userId = employeesDOs.get(0).getDingId();
                    if (userId == null || "".equals(userId)) {
                        log.error("姓名: " + empName + "userId: " + userId);
                        continue;
                    }
                    MessageBody.TextBody textBody = new MessageBody.TextBody();
                    textBody.setContent(sb.toString());
                    log.error("==========姓名: " + empName + "userId: " + userId + "异常消息:" + sb.toString());
                }
                log.error("[attendenceAbnormalListener:94.onMessage]:receive message is," + jsonStr);
            }
        }else{
            //获取数据
            String jsonStr = null;
            try {
                jsonStr = textMessage.getText();
            } catch (JMSException e) {
                log.error("AttendenceAbnormalListener:37 消息队列获取消息出错");
            }

            if (jsonStr != null) {
                AbAttendenceMongo abAttendenceMongo = JSON.parseObject(jsonStr, AbAttendenceMongo.class);
                List<AbnormalAttendanceDTO> abnormalAttendanceList = abAttendenceMongo.getAbnormalAttendanceDTOList();
                Map<Integer, Map<String, List<AbnormalAttendanceDTO>>> empIdMap = new HashMap<>();
                for (AbnormalAttendanceDTO abnormalAttendanceDTO : abnormalAttendanceList) {
                    Integer empId = abnormalAttendanceDTO.getEmpId();
                    String abnormalityOfAttendanceDescribe = abnormalAttendanceDTO.getAbnormalityOfAttendanceDescribe();
                    if (empIdMap.get(empId) == null) {
                        empIdMap.put(empId, new HashMap<>());
                    }
                    if (empIdMap.get(empId).get(abnormalityOfAttendanceDescribe) == null) {
                        empIdMap.get(empId).put(abnormalityOfAttendanceDescribe, new ArrayList<>());
                    }
                    empIdMap.get(empId).get(abnormalityOfAttendanceDescribe).add(abnormalAttendanceDTO);
                }

                for (Integer empId : empIdMap.keySet()) {
                    StringBuilder sb = new StringBuilder();
                    Map<String, List<AbnormalAttendanceDTO>> m = empIdMap.get(empId);
                    String empName = "";
                    Set<String> describeSet = m.keySet();
                    Iterator it = describeSet.iterator();
                    while (it.hasNext()) {
                        List<AbnormalAttendanceDTO> abs = m.get(it.next());
                        empName = abs.get(0).getEmployeeName();
                        sb.append(empName + "  ");
                        break;
                    }
                    for (String desStr : describeSet) {
                        sb.append(desStr + ":");
                        List<AbnormalAttendanceDTO> abnormalAttendanceDTOs = m.get(desStr);
                        for (AbnormalAttendanceDTO abnormalAttendanceDTO : abnormalAttendanceDTOs) {
                            sb.append(abnormalAttendanceDTO.getDateStr() + ",");
                        }
                    }
                    EmpCondition empCondition = new EmpCondition();
                    empCondition.setEmpId(empId);
                    List<EmployeesDO> employeesDOs = employeesMapper.findAllEmp(empCondition);
                    if (employeesDOs == null) {
                        continue;
                    }
                    if (employeesDOs.get(0) == null) {
                        continue;
                    }
                    String userId = employeesDOs.get(0).getDingId();
                    if (userId == null || "".equals(userId)) {
                        log.error("姓名: " + empName + "userId: " + userId);
                        continue;
                    }
                    MessageBody.TextBody textBody = new MessageBody.TextBody();
                    textBody.setContent(sb.toString());
                    try {
                        UserMessageHelper.sendMessageToUser(AuthHelper.getAccessToken(), userId, "", Env.AGENT_ID,  MessageType.TEXT, textBody);
                        Thread.sleep(1000);
                        //钉钉接口一分钟只能调用300条
                        count++;
                        if(count>=288){
                            Thread.sleep(1000*60);
                            count=0;
                        }
                    } catch (Exception e) {

                    }
//                    log.error("开始测试异常消息发送日志信息。。。");
//                    log.error("姓名: " + empName + "userId: " + userId + "异常消息:" + sb.toString());
//                    log.error("测试异常消息发送日志信息结束。。。");
                }
                log.error("[attendenceAbnormalListener:94.onMessage]:receive message is," + jsonStr);
            }
        }

    }

}